const Http = require('http');
const Url = require('url');
const Querystring = require('querystring');

module.exports = function(port, hostname) {
    const handles = {};
    const server = Http.createServer((req, res) => {
        route(req, res);
    }).listen(port, hostname);

    console.log("Server running at http://%s:%d/", hostname, port);
    
    this.use = function(path, callback) {
        handles[path] = callback;
        console.log("map handle is %s", path);
    }

    const route = async (req, res) => {
        // 解析url中的参数
        const path = Url.parse(req.url || '/');
        console.log("地址访问: ", path.pathname);
        try {
            const arg = await parse(path, req)
            if (arg) console.log('参数内容: ', arg);
            let method = handles[path.pathname];
            if (!method) method = handles['*'];
            if (method) {
                let result = await method({request: req, response: res,
                    parameters: arg, attributes: {}});
                res.statusCode = 200;
                let cls_name = typeof(result);
                if (cls_name == 'string') {
                    res.setHeader("Content-Type", "text/html;charset=utf-8");
                    res.end(result);
                } else if (cls_name == 'object' && result) {
                    res.setHeader("Content-Type", "application/json;charset=utf-8");
                    res.end(JSON.stringify(result));
                }
            } else {
                res.statusCode = 404;
                res.setHeader("Content-Type", "text/plain;charset=utf-8");
                res.end("Page not found.\n");
            }
        } catch (e) {
            console.log('error: ', e);
            res.statusCode = 500;
            res.setHeader("Content-Type", "text/plain;charset=utf-8");
            res.end("Internal error of the system.\n");
        }
    }

    const parse = async (path, req) => {
        return new Promise((resolve, reject) => {
            if (path.query) console.log('URL 参数: ', path.query);
            let ret = path.query ? Querystring.parse(path.query) : null;
            let body = '';
            req.on('data', function(thunk){
                body += thunk;
            });
            req.on('end', function() {
                if (body) console.log('POST内容: ', body);
                let obj = null;
                try {
                    if(body) obj = JSON.parse(body);
                } catch (e) {
                    reject(e);
                }
                if (obj) ret = {...ret, ...obj};
                if (ret) console.log("访问参数: ", ret);
                resolve(ret);
            });
            req.on('error', (e) => reject(e));
        });
    };
    
}